package com.jihox.abookpro;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//import org.omg.CORBA.PRIVATE_MEMBER;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.WindowManager.BadTokenException;
import android.widget.Toast;

import com.igexin.sdk.PushManager;
import com.jihox.abookpro.R;
import com.jihox.abookpro.util.AndroidImageFile;
import com.jihox.abookpro.util.DBManager;
import com.jihox.abookpro.util.NativeImageLoader;
import com.jihox.abookpro.view.JHProgressDialog;

public class BaseActivity extends Activity{	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 添加Activity到堆栈
		MyApplication.getInstance().addActivity(this);
		//个推
		PushManager.getInstance().initialize(this.getApplicationContext());
		
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 结束Activity&从栈中移除该Activity
		if(dbMgr!=null)
			dbMgr.closeDB(); 
		MyApplication.getInstance().finishActivity(this);
	}

	protected boolean firstScanFlag = true;
	private final static int SCAN_OK = 1;
	protected final static int LOAD_OK = 2;
	protected JHProgressDialog mJHProgressDialog = null;
	protected JHProgressDialog loadAlbumPicPD = null;
	private DBManager dbMgr; 
	List<AndroidImageFile> listToBeRemoved = new ArrayList<AndroidImageFile>();
	List<AndroidImageFile> listToBeAdded = new ArrayList<AndroidImageFile>();
	List<AndroidImageFile> listToBeUpdated = new ArrayList<AndroidImageFile>();
	protected Handler mHandler = new Handler(){
		@Override
		public synchronized void handleMessage(Message msg) {
			System.gc();
			
			super.handleMessage(msg);
			switch (msg.what) {
			case SCAN_OK:
				//关闭进度条
				if(mJHProgressDialog!=null)
					mJHProgressDialog.dismiss();
				mJHProgressDialog = null;
				scanOKHandle();
				break;
			case LOAD_OK:
				if(loadAlbumPicPD!=null)
					loadAlbumPicPD.dismiss();
				loadAlbumPicPD = null;
				break;
			}
		}
	};
	protected boolean checkSelectedList() {
		Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver mContentResolver = this.getContentResolver();
		if(ShowImageActivity.selectedPhotoList!=null&&ShowImageActivity.selectedPhotoList.size()>0){
			for(AndroidImageFile name:ShowImageActivity.selectedPhotoList){
				Cursor mCursor = mContentResolver.query(mImageUri,null,
						MediaStore.Images.Media.DATA+"=? ",new String[]{name.getPath()},null);
				if(!mCursor.moveToFirst()){
					mCursor.close();
					return false;
				}else{
					mCursor.moveToFirst();
					int modifiedDate = mCursor.getInt(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED));
					int orientation = mCursor.getInt(mCursor
							.getColumnIndex(MediaStore.Images.Media.ORIENTATION));
					mCursor.close();
					if(name.getOrientation()!=orientation||name.getModifiedDate()!=modifiedDate)
						return false;
				}
			}
		}
		return true;
	}
	/**
	 * 利用ContentProvider扫描手机中的图片，此方法在运行在子线程中
	 */
	protected static HashMap<String, List<AndroidImageFile>> mGroupMap = new HashMap<String, List<AndroidImageFile>>();
	protected synchronized void getImages() {
		if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
			showToast( getResources().getString(R.string.T_NoSDCard));
			return;
		}
		//		sendBroadcast(new Intent(//刷新contentprovider
		//				Intent.ACTION_MEDIA_MOUNTED,
		//				Uri.parse("file://" + Environment.getExternalStorageDirectory())));
		//显示进度条
		if(mJHProgressDialog==null){
			try{
				mJHProgressDialog = JHProgressDialog.show(this, null,getResources().getString(R.string.T_Loading) );
			}catch(BadTokenException ex){
				Log.i("BadTokenExceptionBadTokenException","BadTokenExceptionBadTokenExceptionBadTokenException");
			}
		}
		mHandler.post(loadImagesViaContentProvider);
	}
	protected void loadImageProgressBar(){
		if(mJHProgressDialog==null){
			try{
				loadAlbumPicPD = JHProgressDialog.show(this, null, getResources().getString(R.string.T_CreatingAlbum));
			}catch(BadTokenException ex){
				Log.i("BadTokenExceptionBadTokenException","BadTokenExceptionBadTokenExceptionBadTokenException");
			}
		}
	} 
	Runnable loadImagesViaContentProvider = new Runnable() {
		@Override
		public void run() {
			//						Uri mImageUri = MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI;
			Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
			ContentResolver mContentResolver = BaseActivity.this.getContentResolver();

			//只查询jpeg和png的图片
			//				Cursor mCursor = mContentResolver.query(mImageUri, null,
			//						MediaStore.Images.Media.MIME_TYPE + "=? or "
			//						//								+MediaStore.Images.Media.MIME_TYPE + "=? or "
			//						+ MediaStore.Images.Media.MIME_TYPE + "=? or "
			//						+ MediaStore.Images.Media.MIME_TYPE + "=? or "
			//						+ MediaStore.Images.Media.MIME_TYPE + "=? ",
			//						new String[] { "image/jpeg", "image/jpg","image/png","image/bmp"}, MediaStore.Images.Media.DATE_MODIFIED+" DESC");
			Cursor mCursor = mContentResolver.query(mImageUri,null,
					null,null,MediaStore.Images.Media.DATE_MODIFIED+" DESC");
			//						Cursor mCursor = mContentResolver.query(mImageUri,null,
			//										null,null,null);
			mGroupMap.clear();

			List<AndroidImageFile> allOriginalAIF = new ArrayList<AndroidImageFile>();
			if (mCursor!=null){
				while (mCursor.moveToNext()) {
					//获取图片的路径
					String path = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATA));
					String folderName = path.substring(0, path.lastIndexOf("/"));
					int modifiedDate = mCursor.getInt(mCursor
							.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED));
					String parentName = mCursor.getString(mCursor
							.getColumnIndex(MediaStore.Images.Media.BUCKET_DISPLAY_NAME));
					int orientation = mCursor.getInt(mCursor
							.getColumnIndex(MediaStore.Images.Media.ORIENTATION));
					AndroidImageFile aif = new AndroidImageFile();
					aif.setFolderName(parentName);
					aif.setPath(path);
					aif.setModifiedDate(modifiedDate);
					aif.setOrientation(orientation);
					boolean duplicateFlag = false;
					for(AndroidImageFile aiff:allOriginalAIF){
						if(aiff.equals(aif)){
							duplicateFlag = true;
							break;
						}
					}
					if(!duplicateFlag){
						allOriginalAIF.add(aif);
					}
					//根据父路径名将图片放入到mGruopMap中
					if (!mGroupMap.containsKey(folderName)) {//防止有不同的目录下同名的图片父文件夹
						List<AndroidImageFile> childList = new ArrayList<AndroidImageFile>();
						childList.add(aif);
						mGroupMap.put(folderName, childList);
					} else {
						mGroupMap.get(folderName).add(aif);
					}
				}
				mCursor.close();
				checkImageUpdates(allOriginalAIF );
			}

			//通知Handler扫描图片完成
			mHandler.sendEmptyMessage(SCAN_OK);
		}

		private void checkImageUpdates(List<AndroidImageFile> allOriginalAIF) {
			dbMgr = new DBManager(BaseActivity.this);
			List<AndroidImageFile> allThumbnails = dbMgr.queryAllThumbnails();
			listToBeRemoved.clear();
			listToBeAdded.clear();
			listToBeUpdated.clear();

			for(AndroidImageFile aif : allThumbnails){
				boolean findFlag = false;
				for(AndroidImageFile aiff:allOriginalAIF){
					if(aiff.equals(aif) ){
						findFlag = true;
						if(aiff.getModifiedDate()!=aif.getModifiedDate()||aiff.getOrientation()!=aif.getOrientation()){
							listToBeUpdated.add(aif);
						}
						break;
					}
				}
				if(!findFlag){
					listToBeRemoved.add(aif);
				}
			}

			for(AndroidImageFile aiff:allOriginalAIF){
				boolean findFlag = false;
				for(AndroidImageFile aif:allThumbnails){
					if(aiff.equals(aif)){
						findFlag = true;
						break;
					}
				}
				if(!findFlag){
					listToBeAdded.add(aiff);
				}
			}
			dbMgr.addThumbnails(listToBeAdded);
			String dirPath = Environment.getExternalStorageDirectory()+NativeImageLoader.jihoxUrl;
			for(AndroidImageFile aif : listToBeUpdated){
				dbMgr.updateThumbnails(aif);
				NativeImageLoader.getInstance().removeItemFromCache(aif.getPath());
				NativeImageLoader.getInstance().removeItemFromCache(aif.getPath()+"-detail");
				//				if(ShowImageActivity.selectedPhotoList!=null){
				//					for(AndroidImageFile selected : ShowImageActivity.selectedPhotoList){
				//						if(selected.equals(aif)){
				//							ShowImageActivity.selectedPhotoList.remove(selected);
				//							break;
				//						}
				//					}
				//				}
				String path = dirPath+"/"+aif.getPath().replace("/", "-");
				File f = new File(path);
				if(f.exists()){
					f.delete();
				}
			}
			for(AndroidImageFile aif : listToBeRemoved){
				dbMgr.deleteOldThumbnails(aif);
				NativeImageLoader.getInstance().removeItemFromCache(aif.getPath());
				NativeImageLoader.getInstance().removeItemFromCache(aif.getPath()+"-detail");
				if(ShowImageActivity.selectedPhotoList!=null){
					for(AndroidImageFile selected : ShowImageActivity.selectedPhotoList){
						if(selected.equals(aif)){
							ShowImageActivity.selectedPhotoList.remove(selected);
							showToast(getResources().getString(R.string.T_PhotoDeleted));
							break;
						}
					}
				}
				String path = dirPath+"/"+aif.getPath().replace("/", "-");
				File f = new File(path);
				if(f.exists()){
					f.delete();
				}
			}
			dbMgr.closeDB(); 
		}
	};
	Toast toast = null;
	protected synchronized void showToast(String message) {
		if(toast==null)
			toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
		else 
			toast.setText(message);
		toast.show();
	}
	protected void scanOKHandle(){
	}
	protected abstract class ImagesObserver extends ContentObserver{
		public ImagesObserver(Handler handler) {
			super(handler);
		}
		public abstract void onChange(boolean selfChange);
	}
	
	protected String getVersion(){
		String version = null;
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			version = info.versionName;			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}
	
	protected String getPhoneInfo() {  
		StringBuffer info = new StringBuffer();
	    TelephonyManager mTm = (TelephonyManager)this.getSystemService(TELEPHONY_SERVICE);  
	    info.append("手机品牌：").append(android.os.Build.BRAND).append(";");
	    info.append("手机型号：").append(android.os.Build.MODEL).append(";");
	    info.append("IMEI：").append(mTm.getDeviceId()).append(";");
	    info.append("IMSI：").append(mTm.getSubscriberId()).append(";");
	    info.append("系统版本：").append(android.os.Build.VERSION.RELEASE);
	    
	    return info.toString();
	}
}
